package com.jason.controller;

import com.jason.pojo.User;
import com.jason.service.UserService;
import com.jason.utils.JWT;
import com.jason.utils.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseData checkUser(String username, String password, HttpServletResponse response) {
        User user = userService.checkUser(username, password);
        if (user != null) {
            ResponseData responseData = ResponseData.ok();
            responseData.putDataValue("user", user);
            String token = JWT.sign(user, 30L * 24L * 3600L * 1000L);
            if (token != null) {
                responseData.putDataValue("token", token);
            }
            Cookie cookie = new Cookie("token", token);
            response.addCookie(cookie);
            return responseData;
        }
        return ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, new String[] { "用户名或密码不正确" });
    }

    @RequestMapping("/getUserInfo")
    public ResponseData getUserInfo(String token) {
        User user = JWT.unsign(token, User.class);
        if (user != null) {
            return ResponseData.ok().putDataValue("user", user);
        }
        return ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, new String[] { "token已过期" });
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseData updateUserInfo(@RequestBody User user, String token) {
        System.out.println(user);
        User userToken = JWT.unsign(token, User.class);
        if (userToken == null) {
            return ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, new String[] { "token已过期" });
        }
        int state = userService.updateUserInfo(user);
        if (state == 1) {
            ResponseData responseData = ResponseData.ok();
            responseData.putDataValue("message", "更新成功");
            return responseData;
        } else {
            return ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, new String[] { "更新失败" });
        }
    }
}
